<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <script src="lib/vue.js"></script>
  <style>
    .active{
      background-color: pink;
    }
    p{
      width: 300px;
    }
  </style>
</head>
<body>
<div id="root">
  <form action="https://www.baidu.com/s" target="_blank">
    <input @focus="isRender=true" @blur="isRender=false" v-model="wd" @keydown.40.38="isActive" @input="search" type="text" autocomplete="off" name="wd"/>
  </form>
  <template v-if="isRender">
    <p :class="{active:activeIndex===index}" v-for="(item,index) in g" :key="item.sa">{{item.q}}</p>
  </template>

</div>
</body>
<script type="module">
  import jsonp from "./lib/jsonp.js";
  Vue.prototype.$jsonp = jsonp;
  // https://www.baidu.com/sugrec?prod=pc&wd=1&cb=jQuery110203078381282478101_
  new Vue({
    el:"#root",
    data:{
      wd:"",
      g:[],
      activeIndex : -1,
      isRender:false
    },
    methods:{
      isActive(e){
        if(e.keyCode===40){
          this.activeIndex++;
          if(this.activeIndex > this.g.length-1){
            this.activeIndex = -1;
          }
          if(this.activeIndex !== -1){
            this.wd = this.g[this.activeIndex].q;
          }else {
            this.wd = this.q;
          }
        }else {
          this.activeIndex--;
          if(this.activeIndex < -1){
            this.activeIndex = this.g.length-1;
          }
          if(this.activeIndex !== -1){
            this.wd = this.g[this.activeIndex].q;
          }else {
            this.wd = this.q;
          }
        }
      },
      async search(e){
        if(this.timer) clearTimeout(this.timer);
        this.timer = setTimeout(async ()=>{
          const result = await this.$jsonp({
            url:"https://www.baidu.com/sugrec",
            params:{
              prod:"pc",
              wd:e.target.value.trim()
            },
            jsonp:"cb"
          });
          this.g = Array.isArray(result.g)?result.g:[];
          this.q = result.q;
        },300)

      }
    }
  })
</script>
</html>